package com.huawei.esdk.tp.interceptor;

import java.util.List;
import java.util.Map;

import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;

import com.huawei.esdk.platform.common.MessageContext;
import com.huawei.esdk.platform.common.ThreadLocalHolder;
import com.huawei.esdk.tp.common.constants.InfoKeys;

public class TPSmcInInterceptor extends AbstractPhaseInterceptor<Message>
{
    public TPSmcInInterceptor()
    {
        super(Phase.POST_PROTOCOL);
    }

    @Override
    public void handleMessage(Message message) throws Fault
    {
        @SuppressWarnings("unchecked")
        Map<String, List<String>> headers = (Map<String, List<String>>) message
                .get(Message.PROTOCOL_HEADERS);

        MessageContext mc = ThreadLocalHolder.get();
        if (mc == null)
        {
            mc = new MessageContext();
            ThreadLocalHolder.set(mc);
        }

        mc.getEntities().put(InfoKeys.SMC_SESSION_ID.toString(),
                decodeSessionId(headers.get("Set-Cookie")));
    }

    private String decodeSessionId(List<String> strList)
    {
        if (strList == null || strList.isEmpty())
        {
            return null;
        }

        for (String str : strList)
        {
            if (str.contains("ASP.NET"))
            {
                String[] cookieItems = str.split(";");
                for (String item : cookieItems)
                {
                    // SMC R2版本SessionId为小写，R3版本为大写
                    if (item.contains("ASP.NET_SessionId") ||
                            item.contains("ASP.NET_SessionID"))
                    {
                        if(item.contains("="))
                        {
                            String[] smcSessions = item.split("=");
                            if(1 < smcSessions.length)
                            return smcSessions[1];
                        }
                    }
                }
            }
        }

        return null;
    }   
}
